/**Transcore is a remote-GUI to Transmission.
Copyright (C) 2009 by Jerry de Swart

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package transcore;

import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author J de Swart (Custombuild@gmail.com)
 */
public class JSONMessage {

	JSONObject req;

	public JSONMessage(String method) {
		req = new JSONObject();
		try {
			req.put("method", method);
			Double randTag = Math.random() * 10000;
			req.put("tag", randTag.intValue());
		} catch (JSONException jsonEx) {
			System.out.println("Ging iets fout met req.put: " + jsonEx.toString());
		}
	}

	//TODO: Replace the String[] with some neater structure
	public void setParams(String[] args) {
		JSONArray params = new JSONArray();
		JSONObject fields = new JSONObject();
		if (args != null) {
			for (Object arg : args) {
				params.put(arg);
			}
		}
		try {
			fields.put("fields", params);
			req.put("arguments", fields);
		} catch (JSONException jsonEx) {
			//TODO: Decent error handling.
			System.out.println("Error in req.put: " + jsonEx.toString());
		}
	}

	public void setPairParams(HashMap<String, Object> args) {
		try {
			req.put("arguments", args);
		} catch (JSONException jsonEx) {
			//TODO: Decent error handling.
			System.out.println("Error in req.put: " + jsonEx.toString());
		}
	}

	public JSONObject getMessage() {
		return req;
	}

	@Override
	public String toString() {
		return req.toString();
	}
}
